package cn.stylefeng.guns.modular.hx.basic.controller;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.node.ZTreeNode;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.model.params.BasicAddressParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicAddressResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicXlbOauth2tokenService;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoodsCode;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicUnitCode;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsCodeParam;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicUnitCodeParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsCodeResult;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicUnitCodeResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicUnitCodeService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import lombok.Data;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 单位分组控制器
 *
 * @author zhucx
 * @Date 2024-01-10 15:07:34
 */
@Controller
@RequestMapping("/hxBasicUnitCode")
public class HxBasicUnitCodeController extends BaseController {

    private String PREFIX = "/hx/basic/hxBasicUnitCode";

    @Autowired
    private HxBasicUnitCodeService hxBasicUnitCodeService;

    @Autowired
    private UserService userService;
    
    @Autowired
    private BasicCustomerService basicCustomerService;

    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/hxBasicUnitCode.html";
    }

    /**
     * 拉取新零帮门店分类页面
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/pickProducts")
    public String pickProducts(Model model) {
        User user = userService.getcurrentUser();
        //查询可选择客户
        model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/pickProducts.html";
    }

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    /**
     * 拉取新零帮门店分类
     *
     * @author
     * @Date 2023-04-20
     */
    @RequestMapping("/products")
    @ResponseBody
    public ResponseData products(String modified_begin , Integer customerId) {
    	User user = userService.getcurrentUser();
//      String url = "https://test-api.xlbsoft.com/api/hxl.open.storegroup.find";
      String url = "https://hxl-api.xlbsoft.com/api/hxl.open.storegroup.find";
      BasicCustomer r = basicCustomerService.getById(customerId);

      if(ToolUtil.isEmpty(r.getGsnumber())) {
  		return ResponseData.error("请维护新零帮公司号");
      }

		BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
		oauth2tokenParam.setDeliverId(r.getDeliverId());
		oauth2tokenParam.setGsnumber(r.getGsnumber());
		BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
		if(oauth2tokenResult != null) {
			if(ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
				JSONObject json = new JSONObject();
				json.put("update_time", modified_begin);
				String post = HttpRequest.post(url)
							.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb())
							.body(json.toString()).execute().body();
				//System.out.println("================json："+json+"========================");
				//System.out.println("================post："+post+"========================");
		    	JSONObject jsonObject = new JSONObject(post);
				if(jsonObject.get("code").toString().equals("0")) {
					JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
					for (Object object : jsonArray) {
						JSONObject jsonObject2 = new JSONObject(object.toString());
						
						HxBasicUnitCodeParam basicUnitCodeParamadd = new HxBasicUnitCodeParam();
						basicUnitCodeParamadd.setStatus("1");
						basicUnitCodeParamadd.setV1("门店");
						basicUnitCodeParamadd.setDeptId(user.getDeptId());
						basicUnitCodeParamadd.setDeliverId(user.getDeliverId());
						basicUnitCodeParamadd.setCreateUser(user.getName());
						
						String id = jsonObject2.get("id").toString();
						if (ToolUtil.isNotEmpty(id)&&!id.equals("null")&&!id.equals("0")) {//id
							basicUnitCodeParamadd.setXlbStoreGroupId(id);
						} else {
							continue;
						}
						
						String parent_id = jsonObject2.get("parent_id").toString();
						if(ToolUtil.isEmpty(parent_id)||parent_id.equals("null")||parent_id.equals("0")) {
							basicUnitCodeParamadd.setPid(0l);
							basicUnitCodeParamadd.setPids("[0],");
						} else {
							if(parent_id.equals(id)) {
								basicUnitCodeParamadd.setPid(0l);
								basicUnitCodeParamadd.setPids("[0],");
							} else {
								HxBasicUnitCodeParam basicUnitCodeParam = new HxBasicUnitCodeParam();
								basicUnitCodeParam.setXlbStoreGroupId(parent_id);
								basicUnitCodeParam.setV1("门店");
								basicUnitCodeParam.setDeptId(user.getDeptId());
								basicUnitCodeParam.setDeliverId(user.getDeliverId());
								basicUnitCodeParam.setOperateId(user.getOperateId());
								HxBasicUnitCodeResult basicUnitCodeResult = hxBasicUnitCodeService.findBySpec(basicUnitCodeParam);
								if(basicUnitCodeResult != null) {
									basicUnitCodeParamadd.setPid(Long.parseLong(basicUnitCodeResult.getId()+""));
									basicUnitCodeParamadd.setPids(basicUnitCodeResult.getPids() + "[" + basicUnitCodeResult.getId() + "],");
								} else {
									continue;
								}
							}
						}
						
						String name = jsonObject2.get("name").toString();
						if (ToolUtil.isNotEmpty(name)&&!name.equals("null")) {
							basicUnitCodeParamadd.setCodeName(name);
						} else {
							continue;
						}
						
						String level = jsonObject2.get("level").toString();
						if (ToolUtil.isNotEmpty(level)&&!level.equals("null")) {
							basicUnitCodeParamadd.setCodeNumber(level);
						} else {
							basicUnitCodeParamadd.setCodeNumber("0");
						}
				    	
						hxBasicUnitCodeService.add(basicUnitCodeParamadd);
					}
				}
			}
		}
        return ResponseData.success();
    }

    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/hxBasicUnitCode_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/hxBasicUnitCode_edit.html";
    }

    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(HxBasicUnitCodeParam hxBasicUnitCodeParam) {
    	User user = userService.getcurrentUser();
    	hxBasicUnitCodeParam.setDeptId(user.getDeptId());
    	hxBasicUnitCodeParam.setDeliverId(user.getDeliverId());
    	hxBasicUnitCodeParam.setCreateUser(user.getName());

        if (ToolUtil.isEmpty(hxBasicUnitCodeParam.getPid()) || hxBasicUnitCodeParam.getPid().equals(0L)) {
        	hxBasicUnitCodeParam.setPid(0L);
        	hxBasicUnitCodeParam.setPids("[0],");
        } else {
            Long pid = hxBasicUnitCodeParam.getPid();
            HxBasicUnitCode temp = hxBasicUnitCodeService.getById(pid);
            String pids = temp.getPids();
            hxBasicUnitCodeParam.setPid(pid);
            hxBasicUnitCodeParam.setPids(pids + "[" + pid + "],");
        }
        this.hxBasicUnitCodeService.add(hxBasicUnitCodeParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(HxBasicUnitCodeParam hxBasicUnitCodeParam) {
    	hxBasicUnitCodeParam.setUpdateUser(userService.getcurrentUser().getName());
        if (ToolUtil.isEmpty(hxBasicUnitCodeParam.getPid()) || hxBasicUnitCodeParam.getPid().equals(0L)) {
        	hxBasicUnitCodeParam.setPid(0L);
        	hxBasicUnitCodeParam.setPids("[0],");
        } else {
            Long pid = hxBasicUnitCodeParam.getPid();
            HxBasicUnitCode temp = hxBasicUnitCodeService.getById(pid);
            String pids = temp.getPids();
            hxBasicUnitCodeParam.setPid(pid);
            hxBasicUnitCodeParam.setPids(pids + "[" + pid + "],");
        }
        this.hxBasicUnitCodeService.update(hxBasicUnitCodeParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(HxBasicUnitCodeParam hxBasicUnitCodeParam) {
    	List<HxBasicUnitCodeResult> list = hxBasicUnitCodeService.likePids(hxBasicUnitCodeParam.getId());
    	for (HxBasicUnitCodeResult r : list) {
    		HxBasicUnitCodeParam p1 = new HxBasicUnitCodeParam();
    		p1.setId(r.getId());
    		hxBasicUnitCodeService.delete(p1);
		}
        this.hxBasicUnitCodeService.delete(hxBasicUnitCodeParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(HxBasicUnitCodeParam hxBasicUnitCodeParam) {
        HxBasicUnitCode detail = this.hxBasicUnitCodeService.getById(hxBasicUnitCodeParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 获取部门的tree列表，ztree格式
     *
     * @author fengshuonan
     * @Date 2018/12/23 4:56 PM
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree(HxBasicUnitCodeParam hxBasicUnitCodeParam) {
    	User user = userService.getcurrentUser();
    	hxBasicUnitCodeParam.setDeptId(user.getDeptId());
    	hxBasicUnitCodeParam.setDeliverId(user.getDeliverId());
    	hxBasicUnitCodeParam.setOperateId(user.getOperateId());
    	if(ToolUtil.isEmpty(hxBasicUnitCodeParam.getV1())) {
    		hxBasicUnitCodeParam.setV1("门店");
    	}
        List<ZTreeNode> tree = this.hxBasicUnitCodeService.tree(hxBasicUnitCodeParam);
		return tree;
    }

    /**
     * 获取部门的tree列表，ztree格式
     *
     * @author fengshuonan
     * @Date 2018/12/23 4:56 PM
     */
    @RequestMapping(value = "/treeo")
    @ResponseBody
    public List<ZTreeNode> treeo(HxBasicUnitCodeParam hxBasicUnitCodeParam) {
    	User user = userService.getcurrentUser();
    	hxBasicUnitCodeParam.setDeptId(user.getDeptId());
    	hxBasicUnitCodeParam.setDeliverId(user.getDeliverId());
    	hxBasicUnitCodeParam.setOperateId(user.getOperateId());
    	if(ToolUtil.isEmpty(hxBasicUnitCodeParam.getV1())) {
    		hxBasicUnitCodeParam.setV1("门店");
    	}
        List<ZTreeNode> tree = this.hxBasicUnitCodeService.tree(hxBasicUnitCodeParam);
        tree.add(ZTreeNode.createParent());
		return tree;
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxBasicUnitCodeParam hxBasicUnitCodeParam,String condition ) {
    	User user = userService.getcurrentUser();
    	hxBasicUnitCodeParam.setDeptId(user.getDeptId());
    	hxBasicUnitCodeParam.setDeliverId(user.getDeliverId());
    	hxBasicUnitCodeParam.setOperateId(user.getOperateId());
        return this.hxBasicUnitCodeService.findPageBySpec(hxBasicUnitCodeParam,condition);
    }

}


